<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr />
    <textarea
      placeholder="请输入要发表的内容(限制120字)"
      maxlength="120"
      v-model="message"
    ></textarea>
    <mt-button type="primary" size="large" @click="addMessage"
      >发表评论</mt-button
    >
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item, i) in comments" :key="i">
        <div class="cmt-title">
          第{{ i + 1 }}楼&nbsp;&nbsp;用户:{{
            item.user_name
          }}&nbsp;&nbsp;发表时间：
          {{ item.add_date | dateFormatter }}
        </div>
        <div class="cmt-body">
          {{ item.content }}
        </div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click="addMore"
      >加载更多</mt-button
    >
  </div>
</template>

<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      message: "",
      pageSize: 5,
      currentPage: 1,
      comments: []
    };
  },
  props: ["id"],
  created() {
    this.queryMessage();
  },
  methods: {
    // 发表评论
    addMessage() {
      // trim()去掉空格
      if (this.message.trim().length === 0) {
        return Toast("内容不能为空!");
      }
      this.$http
        .get("addComments", {
          params: {
            listId: this.id,
            content: this.message.trim(),
            userName: "user" + this.id
          }
        })
        .then(res => {
          if (res.body.message === "ok") {
            var cmt = {
              user_name: "user" + this.id,
              content: this.message.trim(),
              add_date: Date.now()
            };
            this.comments.unshift(cmt);
            this.message = "";
          } else {
            Toast("评论发表失败");
          }
        });
    },
    // 查询评论
    queryMessage() {
      this.$http
        .get("queryMessageById", {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            id: this.id
          }
        })
        .then(result => {
          if (result.status === 200) {
            this.comments = this.comments.concat(result.body.list);
          } else {
            Toast("查询评论失败");
          }
        });
    },
    // 加载更多
    addMore() {
      this.currentPage++;
      this.queryMessage();
    }
  }
};
</script>

<style lang="scss" scoped>
.cmt-container {
  h3 {
    font-size: 16px;
  }
  textarea {
    font-size: 14px;
    height: 85px;
    margin: 0;
  }
  .cmt-list {
    font-size: 13px;
    margin: 5px 0;
    .cmt-item {
      .cmt-title {
        line-height: 30px;
        background-color: #ccc;
      }
      .cmt-body {
        line-height: 35px;
        text-indent: 2em;
      }
    }
  }
}
</style>
